package com.pig4cloud.pig.ads.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ZipUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.pig4cloud.pig.ads.clickhouse3399.mapper.AdAudienceMapper;
import com.pig4cloud.pig.ads.gdt.service.GdtAccesstokenService;
import com.pig4cloud.pig.ads.pig.mapper.ext.TtCustomAudienceMapperExt;
import com.pig4cloud.pig.ads.service.AdAccountService;
import com.pig4cloud.pig.ads.service.TtAccesstokenService;
import com.pig4cloud.pig.ads.service.TtCustomAudienceService;
import com.pig4cloud.pig.ads.utils.DateUtils;
import com.pig4cloud.pig.ads.utils.OEHttpUtils;
import com.pig4cloud.pig.api.dto.AdAudienceDTO;
import com.pig4cloud.pig.api.dto.AllCustomAudienceDTO;
import com.pig4cloud.pig.api.dto.TtCustomAudiencesDTO;
import com.pig4cloud.pig.api.entity.AdAccount;
import com.pig4cloud.pig.api.entity.AllCustomAudience;
import com.pig4cloud.pig.api.entity.ResponseBean;
import com.pig4cloud.pig.api.entity.TtCustomAudience;
import com.pig4cloud.pig.api.enums.CustomAudienceSourceEnum;
import com.pig4cloud.pig.api.enums.CustomAudienceStatusEnum;
import com.pig4cloud.pig.api.enums.CustomAudienceTypeEnum;
import com.pig4cloud.pig.api.proto.DmpDataProto;
import com.pig4cloud.pig.api.util.Constants;
import com.pig4cloud.pig.api.util.MapUtils;
import com.pig4cloud.pig.api.util.RandomUtil;
import com.pig4cloud.pig.api.util.UploadUtils;
import com.pig4cloud.pig.api.vo.AdAudienceVo;
import com.pig4cloud.pig.common.core.constant.enums.PlatformTypeEnum;
import com.pig4cloud.pig.common.core.util.BigDecimalUtil;
import com.pig4cloud.pig.common.core.util.BigDecimalUtils;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.*;
import java.math.BigDecimal;
import java.net.URL;
import java.util.*;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@Log4j2
@Service
@RequiredArgsConstructor
public class TtCustomAudienceServiceImpl extends ServiceImpl<TtCustomAudienceMapperExt, TtCustomAudience> implements TtCustomAudienceService {

	private final TtAccesstokenService ttAccesstokenService;

	private final StringRedisTemplate stringRedisTemplate;

	private final AdAccountService adAccountService;

	private final GdtAccesstokenService gdtAccesstokenService;

	private final AdAudienceMapper adAudienceMapper;
	@Autowired
	private TtCustomAudienceMapperExt customAudienceMapperExt;
	@Value("${tt_custom_audience_download_url}")
	private String downloadUrl;
	//* 下载地址 *//
	@Value("${tt_custom_audience_upload_path}")
	private String uploadPath;
	//* 限制大小 *//
	@Value("${tt_custom_audience_size}")
	private String imgSize;
	// 广点通公共域名
	@Value(value = "${gdt_url}")
	private String gdtUrl;

	private static final int BUFFER_SIZE = 2 * 1024;

	@Override
	public R createDataSource(TtCustomAudiencesDTO ttdto) {


		String advertiserId = ttdto.getAdvertiser_id();
		Map<String, Object> data = new HashMap<>();
		data.put("advertiser_id", advertiserId);

		Map<String, Object> ttmap = new HashMap<>();

		try {
			ttmap = PropertyUtils.describe(ttdto);
		} catch (Exception e) {
			log.error("对象map转化失败！");
		}

		data.putAll(ttmap);


		log.info("===========>data:{}", data);

		String token = ttAccesstokenService.fetchAccesstoken(advertiserId);

		//调用头条接口
		String resultStr = OEHttpUtils.doPost("https://ad.oceanengine.com/open_api/2/dmp/data_source/create/", data, token);
		log.info("===========>resultStr:{}", resultStr);

		ResponseBean resBean = JSON.parseObject(resultStr, ResponseBean.class);
		//调用成功,信息入库
		if(resBean != null && "0".equals(resBean.getCode())){

			stringRedisTemplate.opsForList().leftPush(Constants.TT_REDIS_CUSTOMAUDIENCE_DATASOURCE_LIST_REDIS_KEY, resBean.getData().getString("data_source_id"));

			return R.ok(resBean.getData(), "创建成功，请耐心等待！");
		} else {
			return R.failed(resBean == null ? "人群包创建-数据源创建失败,账户ID["+advertiserId+"]" : resBean.getMessage());
		}
	}

	@Override
	public R pushSelfCustomAudience(@Valid TtCustomAudiencesDTO dto) {
		return push(dto);
	}

    @Override
    public List<TtCustomAudience> getAllThirdIdAndNames() {
        return customAudienceMapperExt.getAllThirdIdAndNames();
    }

    @Override
	public R create(MultipartFile[] file, @Valid TtCustomAudiencesDTO dto) {

		String ymPath = DateUtils.dateToString(new Date(), DateUtils.YYYYMMDD) + "/";

		Map<String, Object> resultMap = this.fileupload(file[0], ymPath);
		if (resultMap == null || resultMap.get("code") == null || Integer.parseInt(String.valueOf(resultMap.get("code"))) != 0){
			return R.failed(resultMap.get("msg"));
		}
		dto.setDownUrl(resultMap.get("downUrl").toString());
		if (StringUtils.isBlank(dto.getData_source_type())) {
			dto.setData_source_type("UID");
		}
		return push(dto);
	}

	private R push(TtCustomAudiencesDTO dto){
		String ymPath = DateUtils.dateToString(new Date(), DateUtils.YYYYMMDD) + "/";
		String advertiserId = dto.getAdvertiser_id();
		Integer dataType = dto.getDataType();//匹配类型，imei等
		DmpDataProto.IdItem.DataType dataTypeEnum = DmpDataProto.IdItem.DataType.valueOf(dataType);

		if(dataTypeEnum == null) {
			log.error("匹配类型传值错误，dataType={}", dataType);
			return R.failed("匹配类型传值错误,账户ID["+dto.getAdvertiser_id()+"]");
		}
		OutputStream outputStream = null;
		try {
			Date now = new Date();

			//获取上传文件的每一行数据，存入list
			List<String> list = readTxtFile(dto.getDownUrl());
			if(CollectionUtils.isEmpty(list)) {
				log.error("文件不存在或者内容为空");
				return R.failed("文件不存在或者内容为空");
			}

			//每10000行压缩成一个txt文件,暂时没生成，存储在flist里面
			List<Map<String, String>> flist = dealFile(list, dataTypeEnum);


			String fileName = DateUtils.dateToString(now, DateUtils.YYYYMMDDHHMMSS) + "_" + SecurityUtils.getUser().getId() + "_" + RandomUtil.generateNumStr(4)+ ".zip";
			String filePathName = uploadPath + ymPath + fileName;
			String realPath = uploadPath + ymPath;
			File filePath = new File(realPath);
			if (!filePath.exists()){
				filePath.mkdirs();
			}
			File zipfile = new File(filePathName);

			outputStream = new FileOutputStream(zipfile);

			//根据flist(多个txt)压缩成zip

			for (Map<String, String> txtMap : flist) {
				String path = txtMap.get("path");
				String name = txtMap.get("name");
				String data = txtMap.get("data");
				//1先生成txt文件后删除
				FileUtil.writeString(data,uploadPath + ymPath + "temp/" + name,"UTF-8");
//				ZipUtil.zip(new File(filePathName),uploadPath + ymPath + name,data);
			}
			// 自有人群包txt文件上传在这个目录  /data/wwwroot/ad-platform/upload/selfCustomAudience/
			// 压缩的文件和媒体人群包同一位置   /data/wwwroot/ad-platform/upload/ttCustomAudience
			//2压缩
			ZipUtil.zip(uploadPath + ymPath + "temp/",filePathName);
			//3删除临时文件
			FileUtil.del(uploadPath + ymPath + "temp/");

			//旧逻辑超过10000行有问题
//			toZip(flist, outputStream);

			// 文件参数
			FileBody zipfilebody = new FileBody(zipfile);
			MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create()
					.addPart("file", zipfilebody);
			// 其他参数
			entityBuilder.addTextBody("advertiser_id", advertiserId);

			//调用头条接口
			String resultStr = OEHttpUtils.doFilePost("https://ad.oceanengine.com/open_api/2/dmp/data_source/file/upload/", entityBuilder, ttAccesstokenService.fetchAccesstoken(advertiserId));
			ResponseBean resBean = JSON.parseObject(resultStr, ResponseBean.class);
			//调用成功,信息入库
			if(resBean != null && "0".equals(resBean.getCode())){
				JSONObject jsonObject = resBean.getData();
				String file_path = jsonObject.getString("file_path");
				String[] strs = new String[] {file_path};
				dto.setFile_paths(strs);
				return this.createDataSource(dto);
			} else {
				return R.failed(resBean == null ? "人群包创建-数据源文件上传失败,账户ID["+dto.getAdvertiser_id()+"]" : resBean.getMessage());
			}
		} catch (Throwable e) {
			log.error("人群包创建异常", e);
			return R.failed("人群包创建异常,账号ID："+dto.getAdvertiser_id());
		} finally {
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (Throwable e) {
					log.error("人群包创建异常", e);
				}
			}
		}
	}

	@Override
	public IPage<AllCustomAudience> getAudienceList(AllCustomAudienceDTO req) {
		IPage<AllCustomAudience> page = new Page<>();
		page.setSize(req.getSize());
		page.setCurrent(req.getCurrent());
		page = getBaseMapper().getAudienceList(page, req);
		//总条数返回并设置在请求page对象中,需设置到返回对象
		page.setTotal(req.getTotal());
		if (!CollectionUtils.isEmpty(page.getRecords())) {
			//处理账号名称、类型名称、来源名称、状态名称
			List<AllCustomAudience> list = page.getRecords();
			//防止不同平台之前的账户ID相同，可能性极低
			Map<Integer,Map<String,String>> accountMap = new HashMap<>();
			//按人群包分组时也显示广告账户
//			if (req.getTarget() != 3) {
				this.getAdName(list,accountMap);
//			}
			list.forEach((audience) -> {
				if (!CollectionUtils.isEmpty(accountMap)) {
					//设置账户名称
					accountMap.get(audience.getMediaType()).forEach((accountId, v) -> {
						if (audience.getAccountId().equals(accountId)) {
							audience.setAccountName(v);
						}
					});
				}
				this.setNums(req,audience);
				this.setNames(audience);
			});
		}
		return page;
	}

	private void setNums(AllCustomAudienceDTO req,AllCustomAudience audience){
		//对应ClickHouse的广告计划表的ctype -- 平台类型:0-3399平台,1-头条,2-百度,3-新数,4-公会,7-UC,8-广点通
		Integer cType = 1;
		//广告计划ID集合
		List<String> ids = Lists.newArrayList();
		//根据广告账户ID、人群包ID查询所关联的广告计划
		List<String> accountIds  = Lists.newArrayList();
		if (req.getTarget() != 1) {
			//当target = 3时，需要带上广告账户条件 并按人群包分组
			// 默认设置当前记录的广告账户ID
			if (req.getTarget() == 2) {
				accountIds.add(audience.getAccountId());
			} else if (req.getTarget() == 3 && !CollectionUtils.isEmpty(req.getAdList())) {
				//按人群包汇总：指当前投放人能看到的广告账户的维度
				// 存在人群包仅属于账户1，但搜索条件按账户1和账户2搜索
				accountIds.addAll(req.getAdList());
			}
			if(audience.getMediaType() == Integer.parseInt(PlatformTypeEnum.TT.getValue())){
				ids = getBaseMapper().selectAdIdsByTt(audience.getCustomAudienceId(),accountIds);
			} else if(audience.getMediaType() == Integer.parseInt(PlatformTypeEnum.GDT.getValue())){
				cType = 8;
				ids = getBaseMapper().selectAdIdsByGdt(audience.getCustomAudienceId(),accountIds);
			}
			if (!CollectionUtils.isEmpty(ids)) {
				//转换时间问clickhouse所需的格式  eg: b.date >= 20200601
				//查询 返点后消耗,曝光量,点击人数
				AdAudienceDTO adAudienceDTO = new AdAudienceDTO();
				if (StringUtils.isNotBlank(req.getStartDate())) {
					adAudienceDTO.setStartDate(Integer.valueOf(req.getStartDate()));
				}
				if (StringUtils.isNotBlank(req.getEndDate())) {
					adAudienceDTO.setEndDate(Integer.valueOf(req.getEndDate()));
				}
				adAudienceDTO.setCType(audience.getMediaType());
				adAudienceDTO.setIds(ids);
				//设置投放人集合
				if (!CollectionUtils.isEmpty(req.getThrowUserList())) {
					List<Integer> userList = req.getThrowUserList().stream().distinct().map(v -> Integer.parseInt(v)).collect(Collectors.toList());
					adAudienceDTO.setThrowUserList(userList);
				}

				List<AdAudienceVo> costVoList = adAudienceMapper.selectCost(adAudienceDTO);
				//查询 新增设备注册数
				List<AdAudienceVo> usrNameNumList = adAudienceMapper.selectUsrNameNum(adAudienceDTO);
				//查询 新增设备付费数
				List<AdAudienceVo> newUuidNumList = adAudienceMapper.selectNewUuidNum(adAudienceDTO);
				//查询 新增设备在次日有登录行为的设备数
				List<AdAudienceVo> retention2List = adAudienceMapper.selectRetentionTwo(adAudienceDTO);

				//设置统计字段的值
				Double costNum = 0.00;
				// 新增设备注册数
				Long usrNameNum = 0L;
				// 新增设备付费数
				Long newUuidNum = 0L;
				// 新增设备在次日有登录行为的设备数
				Long retention2 = 0L;
				if (!CollectionUtils.isEmpty(costVoList)) {
					//累加所有广告计划的返点后消耗，点击数，曝光量
					costNum = costVoList.stream().mapToDouble(AdAudienceVo::getCost).sum();
					Long clickNum = costVoList.stream().mapToLong(AdAudienceVo::getClickNum).sum();
					Long showNum = costVoList.stream().mapToLong(AdAudienceVo::getShowNum).sum();
					audience.setCost(BigDecimalUtils.round(costNum,2));
					audience.setShowNum(showNum);
					audience.setClickNum(clickNum);
					audience.setClickRate(BigDecimalUtils.mul(BigDecimalUtils.divide(clickNum,showNum,4),100L));
				}
				if (!CollectionUtils.isEmpty(usrNameNumList)) {
					usrNameNum = usrNameNumList.stream().mapToLong(AdAudienceVo::getUsrNameNum).sum();
					audience.setUsrNameNum(usrNameNum);
				}
				if (!CollectionUtils.isEmpty(newUuidNumList)) {
					newUuidNum = newUuidNumList.stream().mapToLong(AdAudienceVo::getNewUuidNum).sum();
				}
				if (!CollectionUtils.isEmpty(retention2List)) {
					retention2 = retention2List.stream().mapToLong(AdAudienceVo::getRetention2).sum();
				}
				//计算注册成本，付费率,次留
				if (!usrNameNum.equals(0L)) {
					//注册成本不需要计算百分比
					audience.setRegisterCost(BigDecimalUtils.divide(costNum,usrNameNum));
					audience.setCostRate(BigDecimalUtils.mul(BigDecimalUtils.divide(newUuidNum,usrNameNum,4),100L));
					audience.setNextDayRate(BigDecimalUtils.mul(BigDecimalUtils.divide(retention2,usrNameNum,4),100L));
				}
			}//{ ids.add("-1");}
		}
	}

	private void getAdName(List<AllCustomAudience> list, Map<Integer,Map<String,String>> accountMap){
		Map<Integer,List<AllCustomAudience>> mediaMap = list.stream().collect(Collectors.groupingBy(AllCustomAudience::getMediaType));
		mediaMap.forEach((k, v) -> {
			List<String> ids = v.stream().distinct().map(AllCustomAudience::getAccountId).collect(Collectors.toList());
			//查询账户名称
			LambdaQueryWrapper<AdAccount> queryWrapper = new LambdaQueryWrapper<>();
			queryWrapper.and(wrapper -> wrapper.eq(AdAccount::getMediaCode,k));
			queryWrapper.and(wrapper -> wrapper.in(AdAccount::getAdvertiserId, ids));
			List<AdAccount> adAccountList =  adAccountService.list(queryWrapper);
			Map<String,String> map = adAccountList.stream().collect(Collectors.toMap(AdAccount::getAdvertiserId,AdAccount::getAdvertiserName));
			accountMap.put(k,map);
		});
	}


	private void setNames(AllCustomAudience audience){
		if(audience.getMediaType() == Integer.parseInt(PlatformTypeEnum.TT.getValue())){
			audience.setTypeName("");
			audience.setSourceName(CustomAudienceSourceEnum.getNameByKey(audience.getSource()));
			//投放状态
			if ("CUSTOM_AUDIENCE_DELIVERY_STATUS_AVAILABLE".equals(audience.getDeliveryStatus())) {
				audience.setStatusName("可用");
			} else {
				audience.setStatusName("不可用");
			}
		} else if(audience.getMediaType() == Integer.parseInt(PlatformTypeEnum.GDT.getValue())){
			audience.setTypeName(CustomAudienceTypeEnum.getNameByKey(audience.getGdtType()));
			audience.setSourceName("");
			audience.setStatusName(CustomAudienceStatusEnum.getNameByKey(audience.getGdtStatus()));
		}
	}

	@Override
	public R deleteAudience(Long id) {
		//获取人群包基本信息信息
		TtCustomAudience customAudience = super.baseMapper.selectById(id);
		if (customAudience == null) {
			return R.failed("删除失败，人群包不存在");
		}
		ResponseBean resBean = null;
		if (customAudience.getMediaType().equals(Integer.parseInt(PlatformTypeEnum.TT.getValue()))) {
			Map<String, Object> data = new HashMap<String, Object>();
			data.put("advertiser_id", customAudience.getAccountId());
			data.put("custom_audience_id", customAudience.getCustomAudienceId());
			String accessToken = ttAccesstokenService.fetchAccesstoken(customAudience.getAccountId());
			String resultStr = OEHttpUtils.doPost("https://ad.oceanengine.com/open_api/2/dmp/custom_audience/delete/", data, accessToken);
			log.info("头条删除人群包==>resultStr:{}", resultStr);
			resBean = JSON.parseObject(resultStr, ResponseBean.class);
			//调用成功,更新数据库isdel状态
			if(resBean != null && !"0".equals(resBean.getCode())){
				return R.failed(resBean.getData(),resBean.getMessage());
			}
		} else if (customAudience.getMediaType().equals(Integer.parseInt(PlatformTypeEnum.GDT.getValue()))) {
			Map<String, String> paramMap = gdtAccesstokenService.fetchAccesstoken(customAudience.getAccountId());
			if (paramMap == null || StringUtils.isEmpty(paramMap.get("access_token"))) {
				return R.failed("广点通授权失效!");
			}
			Map<String, Object> data = new HashMap<String, Object>();
			data.put("account_id", customAudience.getAccountId());
			data.put("audience_id", customAudience.getCustomAudienceId());
			String result = OEHttpUtils.doPost(gdtUrl + "custom_audiences/delete" + "?" + MapUtils.queryString(paramMap), data);
			log.info("广点通删除人群包==>resultStr:{}", result);

			resBean = JSON.parseObject(result, ResponseBean.class);
			//调用成功,更新数据库isdel状态
			if(resBean != null && !"0".equals(resBean.getCode())){
				return R.failed(resBean.getData(),resBean.getMessage());
			}
		}
		if(resBean != null && "0".equals(resBean.getCode())){
			TtCustomAudience update = new TtCustomAudience();
			update.setId(id);
			update.setIsdel(1);
			super.baseMapper.updateById(update);
		}
		return R.ok(resBean.getData(), "删除成功");
	}

	/**
	 * @
	 * @param list
	 * @param dataTypeEnum
	 */
	private List<Map<String, String>> dealFile(List<String> list, DmpDataProto.IdItem.DataType dataTypeEnum) throws Exception{
	    List<Map<String, String>> allflist = new ArrayList<>();

		List<String> newList =new ArrayList<>();
		int j = 1;
		for (int i = 0; i < list.size(); i++) {
		    String kid = list.get(i);
		    newList.add(kid);
		    // 每10000条insert一次
		    if ((i + 1) % 10000 == 0 || (i + 1) == list.size()) {

		        List<Map<String, String>> flist = dealData(newList, dataTypeEnum, j);
		        allflist.addAll(flist);
		        j++;

		        newList.clear();
		    }
		}
		return allflist;
	}

	private List<Map<String, String>> dealData(List<String> list, DmpDataProto.IdItem.DataType dataTypeEnum, int j) throws Exception {
	    List<Map<String, String>> flist = new ArrayList<>();

	    //protocolBuffer序列化
		DmpDataProto.DmpData.Builder builder = DmpDataProto.DmpData.newBuilder();
		for(String id : list) {
			DmpDataProto.IdItem.Builder iditem = DmpDataProto.IdItem.newBuilder();
			iditem.setId(id);
			iditem.setDataType(dataTypeEnum);
			iditem.addTags("");
			builder.addIdList(iditem);
		}
		DmpDataProto.DmpData dmpData = builder.build();
		//序列化
		byte[] dmpDataByte = dmpData.toByteArray();
		//base64加密
    	byte[] contentByte = Base64.getEncoder().encode(dmpDataByte);

        Map<String,String> m1 = new HashMap<>();
        m1.put("path", "");
        m1.put("name", j + ".txt");
        m1.put("data", new String(contentByte, "UTF-8"));
        flist.add(m1);
        return flist;
	}

	private static void toZip(List<Map<String, String>> list, OutputStream out) throws RuntimeException {
        ZipOutputStream zos = null;
        try {
            zos = new ZipOutputStream(out);
            for (Map<String, String> map : list) {
                String path = map.get("path");
                String name = map.get("name");
                String data = map.get("data");
                compress(zos, path, name, data);
            }
        } catch (Exception e) {
            throw new RuntimeException("zip error from ZipUtils", e);
        } finally {
            if (zos != null) {
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

	/**
	 *  根据条件进行压缩
	 */
	private static void compress(ZipOutputStream zos, String path, String name, String data) throws Exception {
	    ByteArrayInputStream in = null;
	    try {
            byte[] buf = new byte[BUFFER_SIZE];
            zos.putNextEntry(new ZipEntry(path + name));
            int len;
            in = new ByteArrayInputStream(data.getBytes("utf-8"));
            while ((len = in.read(buf)) != -1) {
                zos.write(buf, 0, len);
            }
        } catch (Throwable e) {
            throw new Exception("压缩"+name+"失败", e);
        } finally {
			if (zos != null) {
				try {
					zos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
        }
    }

	private static List<String> readTxtFile(String url) {
		List<String> list = new ArrayList<>();
		InputStreamReader read = null;
		BufferedReader bufferedReader = null;
		InputStream is = null;
		try {
			String encoding = "UTF-8";
			is = new URL(url).openStream();

			read = new InputStreamReader(is, encoding);// 考虑到编码格式

			bufferedReader = new BufferedReader(read);
			String lineTxt = null;
			while ((lineTxt = bufferedReader.readLine()) != null) {
				list.add(lineTxt);
			}
		} catch (Exception e) {
			log.error("读取文件内容出错", e);
		} finally {
			if (read != null) {
				try {
					read.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (bufferedReader != null) {
				try {
					bufferedReader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return list;

	}


	private Map<String, Object> fileupload(MultipartFile file, String ymPath) {


		String upPath = uploadPath + ymPath;
		String downUrl = downloadUrl + ymPath;

		//上传图片到本地服务器
		long picSize = 50 * 1024 * 1024;
		if (StringUtils.isNotBlank(imgSize) && !"null".equals(imgSize)) {
			picSize = Long.parseLong(imgSize);
		}
		//上传图片到本地服务器
		return UploadUtils.fileUpload(file, upPath, downUrl, picSize);
	}
}
